package com.colde.salary.serviceImpl;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.colde.salary.common.ServerResponse;
import com.colde.salary.mapper.UserMapper;
import com.colde.salary.model.User;
import com.colde.salary.poi.entity.UserEnity;
import com.colde.salary.service.IUserService;
import com.colde.salary.util.ExcelUtil;
import com.colde.salary.util.SerialUtil;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;


@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper,User> implements IUserService{

	@Override
	public ServerResponse<List<User>> findUserList(String role) {
		List<User> userList = baseMapper.findList(role);
		if(null == userList || userList.size() < 1) {
			return ServerResponse.createByErrorMessage("查询用户失败");
		}
		return ServerResponse.createBySuccess("查询用户成功", userList);
	}

	@Override
	public boolean login(User user) {
		Subject subject = SecurityUtils.getSubject();
		String username = user.getNickname();
		String password = user.getPwd();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		subject.login(token);
		System.out.println("isAuthenticated:"+subject.isAuthenticated());
		return subject.isAuthenticated();
	}

	@Override
	public void export(HttpServletResponse response) {
		List<UserEnity> list = findUserEnityList(null).getData();
		String title = "用户信息汇总";
		String sheetName = "用户信息表";
		String fileName = "用户信息.xls";
		ExcelUtil.exportExcel(list, title, sheetName, UserEnity.class, fileName, response);

	}

	@Override
	public ServerResponse<List<UserEnity>> findUserEnityList(String role) {
		List<UserEnity> list = baseMapper.findUserEnityList(role);
		return ServerResponse.createBySuccess("查询用户成功", list);
	}

	@Override
	public List<UserEnity> importUser(MultipartFile file) {
		if(null==file) {
			return null;
		}
		ImportParams importParams = new ImportParams();        
		// 数据处理        
		importParams.setHeadRows(1);        
		importParams.setTitleRows(1);        
		// 需要验证        
		importParams.setNeedVerfiy(true);
		List<UserEnity> successList = null;
		try {
			ExcelImportResult<UserEnity> result = ExcelImportUtil.importExcelMore(file.getInputStream(), UserEnity.class,importParams);
			successList = result.getList();            
			for (UserEnity demoExcel : successList) {
				demoExcel.setUserId(SerialUtil.getUid());
				System.out.println(demoExcel);
			}        
		} catch (IOException e) {        

		} catch (Exception e) {        

		}
		return successList;
	}

}
